package com.cn.pool1;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.Executor;

import com.alibaba.fastjson.JSON;

import db.User;
import db.UserDaoImpl;

/*
 * worker实现类
 */
public class NioServerWorker extends AbstractNioSelector implements Worker{

	public NioServerWorker(Executor executor, String threadName,
			NioSelectorRunnablePool selectorRunnablePool) {
		super(executor, threadName, selectorRunnablePool);
		// TODO Auto-generated constructor stub
	}

	
	
	//设置多长时间一次询问
	@Override
	protected int select(Selector selector) throws IOException {
		// TODO Auto-generated method stub
		return selector.select(500);
	}

	//执行的业务
	@Override
	protected void process(Selector selector) throws IOException {
		// TODO Auto-generated method stub
		Set<SelectionKey> selectionKeys = selector.selectedKeys();
		//判断是否有事件进入
		if (selectionKeys.isEmpty()) {
			return;
		}
		Iterator<SelectionKey> ite = this.selector.selectedKeys().iterator();
		while (ite.hasNext()) {
			SelectionKey key = (SelectionKey) ite.next();
			//移除，防止重复处理
			ite.remove();
			//得到事件发送的Socket通道
			SocketChannel channel = (SocketChannel) key.channel();
			//数据总长度
			int ret =0;
			boolean failure = true;
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			
			try {
				ret = channel.read(buffer);
				failure = false;
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			//判断是否连接已经断开
			if (ret<=0||failure) {
				key.cancel();
				System.out.println("客户端断开连接");
			} else {
				System.out.println("收到数据："+Thread.currentThread().getName()+"\t"+new String(buffer.array()).trim());
				
				//获取数据
				String oj = new String(buffer.array()).trim();
				//json转换
				MssageUtil mssageUtil =  (MssageUtil) JSON.parseObject(oj,MssageUtil.class);
				ByteBuffer outBuffer = ByteBuffer.allocate(1024);
				UserDaoImpl daoImpl = new UserDaoImpl();
				//查询操作  示例数据： {"list":[],"tyep":{"tp":"find","pm":"1"}}
				if (mssageUtil.getTyep().get("tp").toString().equals("find")) {	
					User user= daoImpl.findUser(mssageUtil.getTyep().get("pm").toString());
					if (user==null) {
						outBuffer = ByteBuffer.wrap("data null".getBytes());
					}else{
						 mssageUtil.getList().add(user);
						 mssageUtil.getTyep().clear();
						 mssageUtil.getTyep().put("tp","ret");
						 String s = JSON.toJSONString(mssageUtil);
						 System.out.println("回执数据："+s);
						 outBuffer = ByteBuffer.wrap(s.getBytes());
					}
					//新增操作  示例数据： {"list":[{"id":1,"password":"123","username":"alle111"}],"tyep":{"tp":"add"}}
				}else if(mssageUtil.getTyep().get("tp").toString().equals("add")){
					String jsons = mssageUtil.getList().get(0).toString();
					User user = JSON.parseObject(jsons,User.class); 
					int num = daoImpl.addUser(user);
					if (num==1) {
						System.out.println("新增成功");
						 outBuffer = ByteBuffer.wrap("add succeed".getBytes());
					}else{
						outBuffer = ByteBuffer.wrap("add error".getBytes());
					}
					
				}else{
					outBuffer = ByteBuffer.wrap("指令有误".getBytes());
				}
				
				//回写数据
				channel.write(outBuffer);//将消息回送给客户端
			}
		}
		
	}
	//加入一个新的socket客户端进来
	@Override
	public void registerNewChannelTask(final SocketChannel channel) {
		// TODO Auto-generated method stub
		final Selector selector = this.selector;
		registerTask(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					//将客户端注册到selector中
					channel.register(selector, SelectionKey.OP_READ);
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
		});
	}

	
}
